package cn.itcast.web.aspect;

import cn.itcast.domain.system.SysLog;
import cn.itcast.domain.system.User;
import cn.itcast.service.system.SysLogService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;
import java.util.Date;

// @Component
@Aspect // 升级为切面类
public class LogAspect {

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private HttpSession session;

    @Autowired
    private SysLogService sysLogService;

    // 环绕通知
    @Around("execution(* cn.itcast.web.controller..*.*(..))")
    public Object aroundLog(ProceedingJoinPoint pjp) throws Throwable {
        // 1.获取用户访问的method方法对象
        MethodSignature signature = (MethodSignature) pjp.getSignature();
        Method method = signature.getMethod();
        // 2.判断方法是是否有@RequestMapping注解
        if (method.isAnnotationPresent(RequestMapping.class)) { // 开启日志记录
            // 创建日志对象
            SysLog sysLog = new SysLog();
            User loginUser = (User) session.getAttribute("loginUser");
            sysLog.setUserName(loginUser==null?"匿名":loginUser.getUserName()); // 登录人名称
            sysLog.setIp(request.getRemoteAddr()); // 登录人ip
            sysLog.setTime(new Date()); // 操作时间
            sysLog.setMethod(method.getName()); // 操作方法
            RequestMapping requestMapping = method.getAnnotation(RequestMapping.class);
            sysLog.setAction(requestMapping.name());// @RequestMapping( name = "用户登录")
            sysLog.setCompanyId(loginUser==null?null:loginUser.getCompanyId()); // 登录人企业id
            sysLog.setCompanyName(loginUser == null ? null : loginUser.getCompanyName()); // 登录人企业id

            sysLogService.save(sysLog);
        }

        // 调用目标对象原有的功能
        return pjp.proceed();
    }
}
